package com.iha.pongzor.gui;

import com.iha.pongzor.R;
import com.iha.pongzor.data.HighScore;
import com.iha.pongzor.database.HighscoreTable;
import com.iha.pongzor.ContentProvider.HighScoreDB_CP;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.ViewFlipper;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;

public class HighscoreActivity extends FragmentActivity implements OnTouchListener {

	// private List<Map<String, String>> hsData;

	float downXValue = 0;

	private SimpleCursorAdapter offlineAdapter;
	private HighScoreLoader offlineLoader;
	private SimpleCursorAdapter onlineAdapter;
	private HighScoreLoader onlineLoader;

	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.highscore);

		Intent i = getIntent();
		boolean initializeDB = i.getBooleanExtra("InitializeDB", false);
		if (initializeDB == true) {
			List<HighScore> hsListLocal = createDummyData(null);
			saveHighScore(hsListLocal);
		}
		boolean clearDB = i.getBooleanExtra("ClearDB", false);
		if (clearDB == true) {
			Uri uri = Uri.withAppendedPath(HighScoreDB_CP.CONTENT_URI, "/offline");
			getContentResolver().delete(uri, null, null);
		}
		
		ListView lv_local = (ListView) findViewById(R.id.highscore_local_list);
		ListView lv_online = (ListView) findViewById(R.id.highscore_online_list);

		fillData();

		lv_local.setAdapter(offlineAdapter);
		lv_online.setAdapter(onlineAdapter);

		((ViewFlipper) findViewById(R.id.highscore_ViewFlipper)).setOnTouchListener(this);

	}

	public void saveHighScore(List<HighScore> highscore) {

		for (int i = 0; i < highscore.size(); i++) {
			saveHighScore(highscore.get(i));
		}

	}

	public void saveHighScore(HighScore highscore) {
		ContentValues values = new ContentValues();
		values.put(HighscoreTable.COLUMN_NAME, highscore.getName());
		values.put(HighscoreTable.COLUMN_SCORE, highscore.getScore());
		values.put(HighscoreTable.COLUMN_SECONDS, highscore.getSeconds());
		values.put(HighscoreTable.COLUMN_date, highscore.getDate());

		Uri uri = Uri.withAppendedPath(HighScoreDB_CP.CONTENT_URI, "/offline");
		getContentResolver().insert(uri, values);
	}

	private void fillData() {

		// Fields from the database (projection)
		// Must include the _id column for the adapter to work
		String[] from = new String[] { HighscoreTable.COLUMN_NAME, HighscoreTable.COLUMN_SCORE };
		// Fields on the UI to which we map
		int[] to = new int[] { R.id.HighScore_playerName, R.id.HighScore_playerScore };

		offlineAdapter = new SimpleCursorAdapter(this, R.layout.highscore_list_field, null, from, to, 0);
		offlineLoader = new HighScoreLoader(this, offlineAdapter, Uri.withAppendedPath(HighScoreDB_CP.CONTENT_URI, "/offline"));
		getSupportLoaderManager().restartLoader(0, null, offlineLoader);

		onlineAdapter = new SimpleCursorAdapter(this, R.layout.highscore_list_field, null, from, to, 0);
		onlineLoader = new HighScoreLoader(this, onlineAdapter, Uri.withAppendedPath(HighScoreDB_CP.CONTENT_URI, "/online"));
		getSupportLoaderManager().restartLoader(1, null, onlineLoader);

	}

	public List<HighScore> createDummyData(List<HighScore> hsList) {
		if (hsList == null)
			hsList = new ArrayList<HighScore>();

		String d = new Date().toLocaleString();
		hsList.add(new HighScore("Hans", 6000, 420, d));
		hsList.add(new HighScore("Lars", 9999, 130, d));
		hsList.add(new HighScore("Linux Thorvaldsen", 1337, 1, d));
		hsList.add(new HighScore("Signe", 2156, 180, d));
		hsList.add(new HighScore("Børge", 88888, 580, d));
		hsList.add(new HighScore("Tina", 123456, 730, d));
		hsList.add(new HighScore("Anette", 1, 10, d));
		hsList.add(new HighScore("Frans", 89, 20, d));

		return hsList;
	}

	public boolean onTouch(View v, MotionEvent event) {

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			// store the X value when the user's finger was pressed down
			downXValue = event.getX();
			break;

		case MotionEvent.ACTION_UP:
			final float MINIMUM_MOVEMENT = 150;
			float difference = event.getX() - downXValue;

			// Get a reference to the ViewFlipper
			ViewFlipper vf = (ViewFlipper) findViewById(R.id.highscore_ViewFlipper);

			if (difference > MINIMUM_MOVEMENT) {
				// Set the animation
				vf.setAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_right));

				// Flip!
				vf.showPrevious();
			} else if (difference < -MINIMUM_MOVEMENT) {
				// Set the animation
				vf.setAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_left));
				// Flip!
				vf.showNext();
			} else
				return true;

			break;

		default:
			break;
		}

		return true;
	}

}

class HighScoreLoader implements LoaderManager.LoaderCallbacks<Cursor> {

	public SimpleCursorAdapter adapter;
	public Uri content_uri;
	public Context context;

	public HighScoreLoader(Context context, SimpleCursorAdapter adapter, Uri content_uri) {
		this.adapter = adapter;
		this.content_uri = content_uri;
		this.context = context;
	}

	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		String[] projection = { HighscoreTable.COLUMN_ID, HighscoreTable.COLUMN_NAME, HighscoreTable.COLUMN_SECONDS, HighscoreTable.COLUMN_date, HighscoreTable.COLUMN_SCORE };
		CursorLoader cursorLoader = new CursorLoader(context, content_uri, projection, null, null, null);

		return cursorLoader;
	}

	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		adapter.changeCursor(data);
	}

	public void onLoaderReset(Loader<Cursor> loader) {
		adapter.changeCursor(null);

	}

}
